'use strict';
var entityCollection = require('./EntityCollection');

var relation = {
};

//添加引用关系
//entityName: 被引用实体名
//refEntityName: 引用实体名
//refField: 引用字段
exports.addReference = function(entityName, refEntityName, refField){
	if (!relation.hasOwnProperty(entityName)){
		relation[entityName] = {};
	}
	if (!relation[entityName].hasOwnProperty(refEntityName)){
		relation[entityName][refEntityName] = [];
	}

	relation[entityName][refEntityName].push(refField);
};

//entityName： 实体名称
//condition：删除条件
exports.deleteVerify = function(entityName, condition, resultHandel){
	if (relation.hasOwnProperty(entityName)) {
		var self = this;
		var entity = entityCollection.getEntity(entityName);
		entity.find(condition, null, null, function(err, deleteRecords){
			if(err){
				resultHandel(err);
			}
			else{
				if(deleteRecords.length == 0){
					resultHandel();
				}
				else{
					var errors = [];
					var references = [];	//被引用的实体记录

					var ids = [];
					for(var i=0; i<deleteRecords.length; i++){
						ids.push(deleteRecords[i]._id);
					}
					var refEntityNameCount = 0;

					for(var refEntityName in relation[entityName]){
						refEntityNameCount++;

						var condition = {$or: []};
				        for(var j=0; j<relation[entityName][refEntityName].length; j++){
				            var filedCondition = {};
				            filedCondition[relation[entityName][refEntityName][j]] = {$in: ids};
				            condition['$or'].push(filedCondition);
				        }
				        
				        var refEntity = entityCollection.getEntity(refEntityName);
				        refEntity.findOne(condition, null, function(err, refRecord){
				        	refEntityNameCount--;

				        	if(err){
								errors.push(err);
							}
							else{
								if(refRecord != null){
									references.push({EntityName: refRecord.collection.name, Record: refRecord});
								}
							}

							if(refEntityNameCount == 0){
								if(errors.length == 0 && references.length == 0){
									resultHandel();
								}
								else{
									if(errors.length > 0){
										resultHandel(errors[0]);
									}
									else{
										resultHandel({
											level: 5,
											title: '删除失败',
											message: entityCollection.getEntity(entityName).Name + " 被 " + entityCollection.getEntity(references[0].EntityName).Name + " 引用，不能删除"
										});
									}
								}
							}
				        });
					}
				}
			}
		});
	}
	else{
		resultHandel();
	}
};